//
//  DownloadListDAO.m
//  ImGuider
//
//  Created by llt on 2017/4/26.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "DownloadListDAO.h"
#import "DBHelper.h"

#define TABLE_NAME [@"download_list_" stringByAppendingString:[UserManager sharedManager].userMd5Identifer ? [UserManager sharedManager].userMd5Identifer : @"imguider"]
#define SID @"_id" // 本地数据库ID
#define LINE_ID @"line_id"

#define UNION_ID @"union_id"

#define DOWNLOAD_TIME @"download_time"// 下载时间
#define UPDATE_TIME @"update_time"// 更新时间
#define JSON @"json"// 数据json

#define DOWNLOAD_STATE @"download_state"// 下载状态


@implementation DownloadListDAO

//-----------------------------------路线表------------------------------------------
+ (BOOL)createTabWithDB:(FMDatabase *)db {
    
    if ([db tableExists:TABLE_NAME]) {
        [db executeUpdate:[NSString stringWithFormat:@"drop table %@",TABLE_NAME]];
    }
    
    NSString *sqlStr = [NSString stringWithFormat:@"create table %@(%@ integer not null primary key autoincrement,%@ text,%@ text,%@ date,%@ date,%@ text)",TABLE_NAME,SID,LINE_ID,UNION_ID,DOWNLOAD_TIME,UPDATE_TIME,JSON];
    BOOL success = [db executeUpdate:sqlStr];
    
    return success;
}

+ (LineModel *)getLineModelWithRS:(FMResultSet *)set {
    
    NSString *json = [set stringForColumn:JSON];
    
    if (json.length == 0) {
        return nil;
    }
    LineModel *model = [LineModel yy_modelWithJSON:json];
    if (!model) {
        [NetAPIManager postPhoneData:@{@"ios_error":json}];
    }
    
    
    model.downloadTime = [set dateForColumn:DOWNLOAD_TIME];
    model.updateTime = [set dateForColumn:UPDATE_TIME];
    model.localID = @([set intForColumn:SID]);
    model.state = [set intForColumn:DOWNLOAD_STATE];
    
    return model;
}


+ (void)getLineModelListBlock:(void (^) (NSArray <LineModel *>*dataArray))block {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        if (![db open]) {
            
            if (block) {
                block(nil);
            }
            return;
        }
        
        if (![db tableExists:TABLE_NAME]) {
            [self createTabWithDB:db];
        }
        
        NSString * sql = [NSString stringWithFormat:@"select * from %@ order by %@ desc",TABLE_NAME,UPDATE_TIME];
        FMResultSet *set = [db executeQuery:sql];
        
        NSMutableArray *loadArray = [NSMutableArray array];
        
        while ([set next]) {
            
            LineModel *model = [self getLineModelWithRS:set];
            
            [loadArray addObject:model];
        }
        [set close];
        if (block) {
            block(loadArray);
        }
        
    }];
}

+ (void)getLineModelListWithState:(DownloadState)state block:(void (^) (NSArray <LineModel *>*dataArray))block {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        if (![db open]) {
            
            if (block) {
                block(nil);
            }
            return;
        }
        
        if (![db tableExists:TABLE_NAME]) {
            [self createTabWithDB:db];
        }
        
        NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_NAME,DOWNLOAD_STATE];
        FMResultSet *set = [db executeQuery:sql,@(state)];
        
        NSMutableArray *loadArray = [NSMutableArray array];
        
        while ([set next]) {
            
            LineModel *model = [self getLineModelWithRS:set];
            if (model) {
                [loadArray addObject:model];
            }
        }
        [set close];
        if (block) {
            block(loadArray);
        }
        
    }];
}

+ (void)getLineModelWithUnionid:(NSString *)unionid Block:(void (^) (LineModel *lineModel))block {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inDatabase:^(FMDatabase *db) {
        
        if (![db open]) {
            
            if (block) {
                
                block(nil);
            }
            return;
        }
        
        if (![db tableExists:TABLE_NAME]) {
            [self createTabWithDB:db];
        }
        
        NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_NAME,UNION_ID];
        FMResultSet *set = [db executeQuery:sql,unionid];
        
        LineModel *lineModel = nil;
        
        if ([set next]) {
            
            lineModel = [self getLineModelWithRS:set];
        }
        [set close];
//        
//        if (lineModel.state == DownloadStateDownloading) {
//            lineModel = [self getLineModelWithlineModel:lineModel db:db];
//        }
        
        if (block) {
            block(lineModel);
        }
    }];
}

//+ (LineModel *)getLineModelWithlineModel:(LineModel *)model db:(FMDatabase *)db {
//
//    LineModel *lineModel = model;
//
//    NSDictionary *senicDict = [self getAllScenicPointWithUnionID:lineModel.unionid db:db];
//
//    NSArray *downloadCompleteArray = senicDict[@(DownloadStateCompleted)];
//
//    NSArray *downloadFailureArray = senicDict[@(DownloadStateFailed)];
//
//    NSArray *suspendArray = senicDict[@(DownloadStateSuspened)];
//
//    NSInteger totalCount = lineModel.records.count;
//
//    if (downloadCompleteArray.count >= totalCount) {
//        lineModel.state = DownloadStateCompleted;
//        lineModel.progress = 1;
//    } else {
//
//        if ((downloadCompleteArray.count + downloadFailureArray.count + suspendArray.count) == totalCount) {
//
//            if (suspendArray.count > 0) {
//
//                lineModel.state = DownloadStateSuspened;
//            } else {
//
//                lineModel.state = DownloadStateFailed;
//            }
//            lineModel.progress = 1;
//        } else {
//
//            lineModel.state = DownloadStateDownloading;
//
//            lineModel.progress = 1.0f * (downloadCompleteArray.count + downloadFailureArray.count) / totalCount;
//        }
//    }
//
//    return lineModel;
//}

+ (void)insertLineModel:(LineModel *)lineModel {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
        
        if (![db open]) {
            return;
        }
        
        if (![db tableExists:TABLE_NAME]) {
            [self createTabWithDB:db];
        }
        
        [DBHelper addCloumnWithDB:db cloumnName:DOWNLOAD_STATE tableName:TABLE_NAME];
        
        NSString *json = [lineModel yy_modelToJSONString];
        
        NSDate *date = [NSDate date];
        
        NSString *selectSql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_NAME,UNION_ID];
        FMResultSet *set = [db executeQuery:selectSql,lineModel.unionid];
        
        if ([set next]) {
            
            LineModel *dbLineModel = [self getLineModelWithRS:set];
            
            DownloadState currentState = dbLineModel.state;
            
            if (currentState != DownloadStateCompleted) {
                currentState = DownloadStateDownloading;
            }
            
            if ([dbLineModel.lineid isEqualToString:lineModel.lineid]) {
                
                NSString *updateSql = [NSString stringWithFormat:@"update %@ set %@ = ?, %@ = ? where %@ = ?",TABLE_NAME,UPDATE_TIME,DOWNLOAD_STATE,SID];
                
                [db executeUpdate:updateSql,date,@(currentState),dbLineModel.localID];
                
            } else {
                
                NSString *updateSql = [NSString stringWithFormat:@"update %@ set %@ = ?,%@ = ?,%@ = ? where %@ = ?",TABLE_NAME,UPDATE_TIME,DOWNLOAD_STATE,JSON,SID];
                
                [db executeUpdate:updateSql,date,@(currentState),lineModel.lineid,json,dbLineModel.localID];
            }
            
        } else {
            
            NSString *insertSql = [NSString stringWithFormat:@"insert into %@(%@,%@,%@,%@,%@,%@) values (?,?,?,?,?,?)",TABLE_NAME,LINE_ID,UNION_ID,DOWNLOAD_TIME,UPDATE_TIME,DOWNLOAD_STATE,JSON];
            [db executeUpdate:insertSql,lineModel.lineid,lineModel.unionid,date,date,@(DownloadStateDownloading),json];
            
        }
        [set close];
        lineModel.localID = @([db lastInsertRowId]);
        
    }];
}

+ (void)deleteLineModel:(LineModel *)lineModel {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inDatabase:^(FMDatabase *db) {
        
        if (![db open]) {
            return;
        }
        
        if (![db tableExists:TABLE_NAME]) {
            [self createTabWithDB:db];
        }
        
        NSString *deleteSql = [NSString stringWithFormat:@"delete from %@ where %@ = ?",TABLE_NAME,UNION_ID];
        [db executeUpdate:deleteSql,lineModel.unionid];
        
    }];
}

+ (void)changeLineModelState:(DownloadState)state unionid:(NSString *)unionid {
    
    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
    
    [queue inDatabase:^(FMDatabase *db) {
        
        if ([db open]) {
            
            if (![db tableExists:TABLE_NAME]) {
                [self createTabWithDB:db];
            }
            NSString *updateSql = [NSString stringWithFormat:@"update %@ set %@ = ? where %@ = ?",TABLE_NAME,DOWNLOAD_STATE,UNION_ID];
            
            [db executeUpdate:updateSql,@(state),unionid];
        }
    }];
}

////-----------------------------------景点表------------------------------------------
//
//
//#define TABLE_SCENIC_NAME   [@"scenic_list_" stringByAppendingString:[UserManager sharedManager].userMd5Identifer ? [UserManager sharedManager].userMd5Identifer : @"imguider"]
//
////#define SID @"_id" // 本地数据库ID
////
////#define UNION_ID @"union_id"
//
////#define DOWNLOAD_TIME       @"download_time"// 下载时间
////#define DOWNLOAD_STATE @"download_state"// 下载状态
//
//#define SCENIC_ID           @"scenic_id"// 景点ID
//#define SCENIC_PLAYPATH     @"playpath"
//
//+ (BOOL)createScenicTabWithDB:(FMDatabase *)db {
//    
//    if ([db tableExists:TABLE_SCENIC_NAME]) {
//        [db executeUpdate:[NSString stringWithFormat:@"drop table %@",TABLE_SCENIC_NAME]];
//    }
//    
//    NSString *sqlStr = [NSString stringWithFormat:@"create table %@(%@ integer not null primary key autoincrement,%@ text,%@ text,%@ date,%@ integer,%@ text)",TABLE_SCENIC_NAME,SID,SCENIC_ID,UNION_ID,DOWNLOAD_TIME,DOWNLOAD_STATE,SCENIC_PLAYPATH];
//    BOOL success = [db executeUpdate:sqlStr];
//    
//    return success;
//}
//
//+ (ScenicPoint *)getScenicPointWithRS:(FMResultSet *)set {
//    
//    ScenicPoint *point = [[ScenicPoint alloc] init];
//    
//    point.localID = @([set intForColumn:SID]);
//    point.ID = [set stringForColumn:SCENIC_ID];
//    
//    point.playpath = [set stringForColumn:SCENIC_PLAYPATH];
//    point.state = [set intForColumn:DOWNLOAD_STATE];
//    
//    point.downloadTime = [set dateForColumn:DOWNLOAD_TIME];
//    
//    return point;
//}
//
//+ (void)getAllScenicPointWithUnionID:(NSString *)unionid Block:(void (^) (NSArray <ScenicPoint *>* scenicPointArray))block {
//    
//    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
//    
//    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
//        
//        if (![db open]) {
//            
//            if (block) {
//                block(nil);
//            }
//            return;
//        }
//        
//        if (![db tableExists:TABLE_SCENIC_NAME]) {
//            [self createScenicTabWithDB:db];
//        }
//        
//        NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_SCENIC_NAME,UNION_ID];
//        FMResultSet *set = [db executeQuery:sql,unionid];
//        
//        NSMutableArray *resultArray = [NSMutableArray array];
//        
//        while ([set next]) {
//            
//            ScenicPoint *scenicPoint = [self getScenicPointWithRS:set];
//            
//            [resultArray addObject:scenicPoint];
//        }
//        
//        if (block) {
//            block(resultArray);
//        }
//        [set close];
//        
//    }];
//    
//}
//
////+ (void)getDownloadScenicPointWithUnionID:(NSString *)unionid state:(DownloadState)state Block:(void (^) (NSArray <ScenicPoint *>* scenicPointArray))block {
////
////
////    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
////
////    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
////
////        if (![db open]) {
////
////            if (block) {
////                block(nil);
////            }
////            return;
////        }
////
////        NSArray *resultArray = [self getDownloadScenicPointWithUnionID:unionid state:state db:db];
////
////        if (block) {
////            block(resultArray);
////        }
////    }];
////}
//
//+ (void)getDownloadScenicPointWithState:(DownloadState)state Block:(void (^) (NSArray <ScenicPoint *>* scenicPointArray))block {
//    
//    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
//    
//    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
//        
//        if (![db open]) {
//            
//            if (block) {
//                block(nil);
//            }
//            return;
//        }
//        if (![db tableExists:TABLE_SCENIC_NAME]) {
//            [self createScenicTabWithDB:db];
//        }
//        NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ <= ?",TABLE_SCENIC_NAME,DOWNLOAD_STATE];
//        
//        FMResultSet *set = [db executeQuery:sql,@(state)];
//        
//        NSMutableArray *resultArray = [NSMutableArray array];
//        
//        while ([set next]) {
//            
//            ScenicPoint *scenicPoint = [self getScenicPointWithRS:set];
//            
//            [resultArray addObject:scenicPoint];
//        }
//        [set close];
//        
//        if (block) {
//            block(resultArray);
//        }
//    }];
//}
//
//+ (void)getScenicePointWithScenicID:(NSString *)scenicid Block:(void (^) (ScenicPoint *scenicPoint))block {
//    
//    
//    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
//    
//    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
//        
//        if (![db open]) {
//            
//            if (block) {
//                block(nil);
//            }
//            return;
//        }
//        if (![db tableExists:TABLE_SCENIC_NAME]) {
//            [self createScenicTabWithDB:db];
//        }
//        NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_SCENIC_NAME,SCENIC_ID];
//        
//        FMResultSet *set = [db executeQuery:sql,scenicid];
//        
//        
//        ScenicPoint *scenicPoint = nil;
//        
//        if ([set next]) {
//            
//            scenicPoint = [self getScenicPointWithRS:set];
//        }
//        [set close];
//        
//        if (block) {
//            block(scenicPoint);
//        }
//    }];
//}
//
//
//+ (void)sceniceDownloadStateForURL:(NSString *)URLStr Block:(void (^) (DownloadState state))block {
//    
//    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
//    
//    [queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
//        
//        if (![db open]) {
//            
//            if (block) {
//                block(0);
//            }
//            return;
//        }
//        if (![db tableExists:TABLE_SCENIC_NAME]) {
//            [self createScenicTabWithDB:db];
//        }
//        NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_SCENIC_NAME,SCENIC_PLAYPATH];
//        
//        FMResultSet *set = [db executeQuery:sql,URLStr];
//        
//        DownloadState state = 0;
//        
//        if ([set next]) {
//            
//            state = [set intForColumn:DOWNLOAD_STATE];
//        }
//        [set close];
//        
//        if (block) {
//            block(state);
//        }
//    }];
//}
//
//// DownloadStateCompleted
////DownloadStateFailed
////DownloadStateSuspened
//+ (NSDictionary *)getAllScenicPointWithUnionID:(NSString *)unionid db:(FMDatabase *)db {
//
//    NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_SCENIC_NAME,UNION_ID];
//
//    FMResultSet *set = [db executeQuery:sql,unionid];
//
//    NSMutableArray *CompletedArray = [NSMutableArray array];
//    NSMutableArray *FailedArray = [NSMutableArray array];
//    NSMutableArray *SuspeneddArray = [NSMutableArray array];
//
//    while ([set next]) {
//
//        ScenicPoint *scenicPoint = [self getScenicPointWithRS:set];
//
//        if (scenicPoint.state == DownloadStateCompleted) {
//
//            [CompletedArray addObject:scenicPoint];
//        }
//        if (scenicPoint.state == DownloadStateFailed) {
//
//            [FailedArray addObject:scenicPoint];
//        }
//        if (scenicPoint.state == DownloadStateSuspened) {
//
//            [SuspeneddArray addObject:scenicPoint];
//        }
//    }
//
//    [set close];
//
//    return @{@(DownloadStateCompleted):CompletedArray,
//             @(DownloadStateFailed):FailedArray,
//             @(DownloadStateSuspened):SuspeneddArray};
//}
//
////+ (NSArray *)getDownloadScenicPointWithUnionID:(NSString *)unionid state:(DownloadState)state db:(FMDatabase *)db {
////
////    if (![db tableExists:TABLE_SCENIC_NAME]) {
////        [self createScenicTabWithDB:db];
////    }
////
////    NSString * sql = [NSString stringWithFormat:@"select * from %@ where %@ = ? and %@ = ?",TABLE_SCENIC_NAME,UNION_ID,DOWNLOAD_STATE];
////
////    FMResultSet *set = [db executeQuery:sql,unionid,@(state)];
////
////    NSMutableArray *resultArray = [NSMutableArray array];
////
////    while ([set next]) {
////
////        ScenicPoint *scenicPoint = [self getScenicPointWithRS:set];
////
////        [resultArray addObject:scenicPoint];
////    }
////    [set close];
////
////    return resultArray;
////}
//
//+ (void)insertScenicPoint:(ScenicPoint *)scenicPoint unionID:(NSString *)unionid db:(FMDatabase *)db {
//    
//    if (!scenicPoint) {
//        return;
//    }
//    if (![db tableExists:TABLE_SCENIC_NAME]) {
//        [self createScenicTabWithDB:db];
//    }
//    
//    NSDate *date = [NSDate date];
//    
//    NSString *selectSql = [NSString stringWithFormat:@"select * from %@ where %@ = ?",TABLE_SCENIC_NAME,SCENIC_PLAYPATH];
//    FMResultSet *set = [db executeQuery:selectSql,scenicPoint.playpath];
//    
//    if ([set next]) {
//        [self changeState:DownloadStateWillResume scenicPlaypath:[set stringForColumn:SCENIC_PLAYPATH] db:db];
//        [set close];
//        return;
//    }
//    [set close];
//    NSString *insertSql = [NSString stringWithFormat:@"insert into %@(%@,%@,%@,%@,%@) values (?,?,?,?,?)",TABLE_SCENIC_NAME,UNION_ID,DOWNLOAD_TIME,SCENIC_ID,DOWNLOAD_STATE,SCENIC_PLAYPATH];
//    [db executeUpdate:insertSql,unionid,date,scenicPoint.ID,@(DownloadStateWillResume),scenicPoint.playpath];
//    
//    scenicPoint.localID = @([db lastInsertRowId]);
//}
//
//+ (void)deleteScenicWithUnionID:(NSString *)unionid db:(FMDatabase *)db {
//    
//    
//    if (![db tableExists:TABLE_SCENIC_NAME]) {
//        [self createScenicTabWithDB:db];
//        return;
//    }
//    
//    NSString *deleteSql = [NSString stringWithFormat:@"delete from %@ where %@ = ?",TABLE_SCENIC_NAME,UNION_ID];
//    [db executeUpdate:deleteSql,unionid];
//}
//
//
//+ (void)changeState:(DownloadState)state scenicPlaypath:(NSString *)playPath {
//    
//    FMDatabaseQueue *queue = [DBHelper getDatabaseQueue];
//    
//    [queue inDatabase:^(FMDatabase *db) {
//        
//        if ([db open]) {
//            
//            if (![db tableExists:TABLE_SCENIC_NAME]) {
//                [self createScenicTabWithDB:db];
//            }
//            [self changeState:state scenicPlaypath:playPath db:db];
//        }
//    }];
//}
//
//+ (void)changeState:(DownloadState)state scenicPlaypath:(NSString *)playPath db:(FMDatabase *)db {
//    
//    NSString *updateSql = [NSString stringWithFormat:@"update %@ set %@ = ? where %@ = ?",TABLE_SCENIC_NAME,DOWNLOAD_STATE,SCENIC_PLAYPATH];
//    
//    [db executeUpdate:updateSql,@(state),playPath];
//}

@end
